<template>
  <div>
    <!-- 面包屑导航 -->
    <params-breadcrumb />

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="注意: 只允许设置第三级分类设置相关参数!"
        type="warning"
        :closable="false"
        show-icon
      />

      <!-- 选择商品分类区 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类: &nbsp;</span>
          <!-- 选择商品分类级联 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            ref="paramsCascaderRef"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParamsDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClosed(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <!-- 索引列 -->
            <el-table-column type="index" label="#" />
            <el-table-column label="参数名称" prop="attr_name" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row.attr_id)"
                  icon="el-icon-edit"
                  size="mini"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="removeParam(scope.row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            @click="addParamsDialogVisible = true"
            size="mini"
            :disabled="isBtnDisable"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClosed(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#" />
            <el-table-column label="属性名称" prop="attr_name" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row.attr_id)"
                  icon="el-icon-edit"
                  size="mini"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="removeParam(scope.row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogClosed"
    >
      <!-- 添加参数表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsDialogClosed"
    >
      <!-- 修改参数表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ParamsBreadcrumb from './childComps/ParamsBreadcrumb.vue'

import {
  getCateList,
  getAttributes,
  addParams,
  getParamById,
  editParams,
  removeParam,
  submitTag,
} from 'network/params'

export default {
  components: { ParamsBreadcrumb },
  name: 'Params',
  data() {
    return {
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      selectedCateKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      addForm: {
        attr_name: '',
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editParamsDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    isBtnDisable() {
      return this.selectedCateKeys.length !== 3
    },
    cateId() {
      if (this.selectedCateKeys.length === 3) return this.selectedCateKeys[2]
      return null
    },
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    },
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const res = await getCateList()
      if (res.meta.status !== 200)
        return this.$message.error('获取商品列表失败!')
      this.cateList = res.data
    },
    handleChange() {
      // 限制选择为三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getAttributes(this.cateId, this.activeName)
      this.$refs.paramsCascaderRef.dropDownVisible = false
    },
    handleTabClick() {
      this.getAttributes(this.cateId, this.activeName)
    },
    async getAttributes(id, sel) {
      const res = await getAttributes(id, sel)
      if (res.meta.status !== 200)
        return this.$message.error('获取参数列表失败!')
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addParamsDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const res = await addParams(
          this.cateId,
          this.addForm.attr_name,
          this.activeName
        )
        if (res.meta.status !== 201) return this.$message.error('添加参数失败!')
        this.$message.success('添加参数成功!')
        this.addParamsDialogVisible = false
        this.getAttributes(this.cateId, this.activeName)
      })
    },
    async showEditDialog(id) {
      const res = await getParamById(this.cateId, id, this.activeName)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取参数失败!')
      this.editForm = res.data
      this.editParamsDialogVisible = true
    },
    editParamsDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const res = await editParams(
          this.cateId,
          this.editForm.attr_id,
          this.editForm.attr_name,
          this.activeName
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改参数失败!')
        this.$message.success('修改参数成功!')
        this.getAttributes(this.cateId, this.activeName)
        this.editParamsDialogVisible = false
      })
    },
    async removeParam(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') return this.$message.info('已取消删除!')
      const res = await removeParam(this.cateId, attr_id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败!')
      this.$message.success('删除参数成功!')
      this.getAttributes(this.cateId, this.activeName)
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        return
      }
      // 输入数据合法的处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      this.submitTag(row)
    },
    showInput(row) {
      row.inputVisible = true
      // 是文本框自动获得焦点
      // 当页面中的元素被重新渲染之后,才会调用$nextTick的回调函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async submitTag(row) {
      const res = await submitTag(this.cateId, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' '),
      })

      if (res.meta.status !== 200) return this.$message.error('添加标签失败!')
      this.$message.success('添加参数成功')
    },
    tagClosed(index, row) {
      row.attr_vals.splice(index, 1)
      this.submitTag(row)
    },
  },
}
</script>

<style lang="less">
.cat-opt {
  margin: 15px 0;
}

.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 120px;
}
// 去除单选框
.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}

.el-cascader-panel .el-radio__input {
  visibility: hidden;
}

.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>>
